﻿//Account.cpp
#include"Account.hh"
#include<fstream>
#include<iomanip>
#include<sstream>
#include<chrono>
#ifdef _WIN32
#include<Windows.h>
#endif
namespace Banking {

    //账户类的构造函数实现
    Account::Account(const std::string& id, const std::string& owner, double initialBalance)
        : accountId(id), ownerName(owner), balance(initialBalance)
    {
    }

    //存款操作的实现
    bool Account::deposit(double amount, const std::string& note) {
        //检查是否可以存款以及存款金额是否大于 0
        if (!canDeposit() || amount <= 0) {
            return false;
        }

        balance += amount;  //更新账户余额
        //记录存款交易
        transactions.emplace_back(accountId, "", amount, TransactionType::DEPOSIT, note);
        return true;
    }

    //取款操作的实现
    bool Account::withdraw(double amount, const std::string& note) {
        //检查是否可以取款、取款金额是否大于 0 以及是否超过账户余额
        if (!canWithdraw() || amount <= 0 || amount > balance) {
            return false;
        }

        balance -= amount;  //更新账户余额
        //记录取款交易
        transactions.emplace_back(accountId, "", amount, TransactionType::WITHDRAWAL, note);
        return true;
    }

    //转账操作的实现
    bool Account::transfer(std::shared_ptr<Account> target, double amount, const std::string& note) {
        //检查目标账户是否存在、转账金额是否大于 0、是否超过账户余额以及是否可以转账到目标账户
        if (!target || amount <= 0 || amount > balance || !canTransferTo(target)) {
            return false;
        }

        balance -= amount;  //更新源账户余额
        target->balance += amount;  //更新目标账户余额

        //记录转账交易到源账户和目标账户
        transactions.emplace_back(accountId, target->getAccountId(), amount, TransactionType::TRANSFER, note);
        target->transactions.emplace_back(accountId, target->getAccountId(), amount, TransactionType::TRANSFER, note);

        return true;
    }

    //生成账户交易报告的实现
    void Account::generateTransactionReport() const {
        SetConsoleOutputCP(CP_UTF8);//Windows系统下设置控制台输出为UTF-8编码
        auto now = std::chrono::system_clock::now();  //获取当前时间
        auto time = std::chrono::system_clock::to_time_t(now);
        std::tm localTime;
        localtime_s(&localTime, &time);
        std::stringstream ss;
        ss << std::put_time(&localTime, "%Y-%m-%d");

        std::string filename = "transactions_" + accountId + "_" + ss.str() + ".txt";  //生成报告文件名
        std::ofstream file(filename);  //打开文件

        if (!file) {
            return;
        }

        //写入报告头部信息
        file << "Transaction Report for Account: " << accountId << "\n"
            << "Account Holder: " << ownerName << "\n"
            << "Current Balance: ¥" << std::fixed << std::setprecision(2) << balance << "\n\n"
            << "Transaction History:\n\n";

        //写入所有交易记录
        for (const auto& transaction : transactions) {
            file << transaction.toString() << "\n";
        }
    }

} //namespace Banking